package net.fkzg.framework.application;

import lombok.extern.slf4j.Slf4j;
import net.fkzg.framework.application.data.StorageDataHelper;
import net.fkzg.framework.util.MD5Util;
import org.smartboot.http.common.utils.StringUtils;
import org.smartboot.http.restful.RestResult;
import org.smartboot.http.restful.annotation.Bean;
import org.smartboot.http.restful.annotation.PostConstruct;

import static net.fkzg.framework.util.Constant.SUPER;

@Slf4j
@Bean
public class ApplicationInitializer {

    @PostConstruct
    public static void init() {
        initRedisConnect();
        initSuperUser();
    }

    private static void initRedisConnect() {
        StorageDataHelper.init();
    }
    private static void initSuperUser() {
        String value = StorageDataHelper.getVal(SUPER, "username");
        if (StringUtils.isEmpty(value)) {
            StorageDataHelper.setVal(SUPER, "username", "admin");
            StorageDataHelper.setVal(SUPER, "password", MD5Util.getMd5String(
                    MD5Util.getMd5String("123456") + MD5Util.getMd5String("admin")
            ));
            log.info("初始化超级管理员账号admin,使用密码123456");
        } else {
            log.info("已存在超级管理员账号:{}", value);
        }
    }

    public static boolean checkSuperUser(String username, String pwdHash) {
        String ru = StorageDataHelper.getVal(SUPER, "username");
        String rp = StorageDataHelper.getVal(SUPER, "password");
        if (ru.equals(username) && rp.equals(pwdHash)) {
            return true;
        }
        return false;
    }

    public static RestResult<?> returnException(int code, String description) throws Exception {
        RestResult<Object> fail = RestResult.fail(description);
        fail.setCode(code);
        return fail;
    }

}
